package org.artifact.builder.design;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class DesignDatabase {
	private DesignConfig designConfig;
	// 数据库的表集合
	private Map<String,DesignTable> tables = new HashMap<>();

	public DesignDatabase(DesignConfig designConfig,String designSourcePath) {
		
		this.designConfig = designConfig;
		
		
		List<File> _tables = FileUtil.loopFiles(designSourcePath, f -> f.getName().endsWith(".xml"));
		for (File _table : _tables) {
			Document dom = XmlUtil.readXML(_table);
			Element design = XmlUtil.getRootElement(dom);
			DesignTable designTable = new DesignTable(design,designConfig);
			this.tables.put(designTable.getTableName(),designTable);
		}
		
		stuffRelation();
	}

	/**
	 * 填充关系
	 */
	private void stuffRelation() {
		tables.forEach((k,v)->{
			List<DesignColumn> columns = v.getColumns();
			for (DesignColumn column : columns) {
				String[] fyArray = StrUtil.split(column.getFk(), ":");
				if (ArrayUtil.isEmpty(fyArray)) {
					continue;
				}
				DesignTable table = tables.get(fyArray[0]);
				if (table != null) {
					DesignRelation relation = new DesignRelation(v, column,Boolean.valueOf(fyArray[1]));
					table.getRelations().add(relation);
					
					
					// 外键索引
					List<DesignColumn> indexColumns = new ArrayList<>();
					indexColumns.add(column);
					v.getIndexs().add(new DesignIndex(indexColumns, Boolean.valueOf(fyArray[1])));
				}
			}
		});
	}
}
